<script lang="ts" setup>
// #region 引入包, 函数和组件
import { userListApi } from '@/business'
import type { UserListData } from '@/interfaces/RequestType'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import type TableList from './components/TableList.vue'
// #endregion

// #region // 使用模块(仓库、路由、父组件参数函数)

// #endregion

// #region // 变量
const tableData = ref<UserListData[]>([]) // 用户列表表格数据
const page = ref(1) // 页面下标
const size = ref(5) // 每页条数
const show = ref(false) // 弹窗显示
const total = ref(0) // 总条数
const formData = ref<UserListData>({
  id: 0,
  username: '',
  realname: '',
  age: 0,
  sex: 0,
  birthday: '',
  avatar: '',
  city: '',
  address: '',
}) // 弹窗表单数据
const showType = ref('新增用户')
const tableListRef = ref<InstanceType<typeof TableList> | null>(null)

// #endregion

// #region // 函数
const getUserList = async (query: { size: number; page: number }) => {
  try {
    const res = await userListApi(query)
    // console.log(res)
    if (res.data.code === 0) {
      tableData.value = res.data.data.users
      total.value = res.data.data.total
    } else {
      ElMessage.error('表格数据获取失败')
    }
  } catch (error) {
    console.log(error)
  }
}
// 点击打开弹窗
const openDialog = (row?: UserListData) => {
  show.value = true
  if (row) {
    formData.value = { ...row }
    showType.value = '编辑用户'
  } else {
    formData.value = {
      id: 0,
      username: '',
      realname: '',
      age: 0,
      sex: 0,
      birthday: '',
      avatar: '',
      city: '',
      address: '',
    }
    showType.value = '新增用户'
  }
}
// #endregion

// #region // 生命周期和vue函数
// 初始调用获取用户列表数据
getUserList({ page: page.value, size: size.value })
// #endregion
</script>

<template>
  <div class="sys_user">
    <table-search
      @openDialog="openDialog"
      :show
      v-model:formData="formData"
      :table="tableListRef?.tableRef"
    ></table-search>
    <table-list
      @openDialog="openDialog"
      @getUserList="getUserList"
      v-model:formData="formData"
      :show
      :query="{ page, size }"
      :tableData
      ref="tableListRef"
    ></table-list>
    <table-pagination
      @getUserList="getUserList"
      v-model:size="size"
      v-model:page="page"
      :total
    ></table-pagination>
    <dialog-pop v-model:formData="formData" :showType v-model:show="show"></dialog-pop>
  </div>
</template>

<style lang="sass" scoped>

</style>
